const { verifyToken } = require('@utils/jwt');
const {MESSAGE_NO_TOKEN, MESSAGE_EXPIRED_TOKEN} = require('@config/config');

const verify = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) { return res.status(401).json({success: false, message: MESSAGE_NO_TOKEN }); } 
  const payload = verifyToken(token);
  if (!payload) { return res.status(403).json({success: false, message: MESSAGE_EXPIRED_TOKEN }); }
  req.user = payload;
  next();
}

module.exports = verify;